<template>
  <template v-if="loaded">
    <div class="particle-setting">
      <div class="header">
        <div class="left">
          <div class="back" @click="back">
            <SvgIcon icon-class="ic_返回" />
            <span>返回</span>
          </div>
        </div>
        <el-button type="primary" @click="saveConfirm"> 保存并退出编辑 </el-button>
      </div>
      <div class="iframe-wrap">
        <ParticleIframe ref="particleIframeRef" />
      </div>
    </div>
  </template>
</template>

<script setup lang="ts">
import { getAbsolutePath } from '@jl/common/utils';
import { createEffect, editEffect } from '@/api/scene';
import { debounce } from 'lodash';
import { retFilePath } from '@/utils';
import ParticleIframe from './particle-setting.vue';

defineOptions({
  name: 'ParticleSetting',
});

interface IProps {
  json: string;
  effect: any;
}

const props = withDefaults(defineProps<IProps>(), {
  json: '',
  effect: null,
});

const emits = defineEmits(['closeHandle']);

interface Resource {
  id: string;
  type: 'js' | 'css';
  url: string;
}

const loaded = ref(false);

const resources: Resource[] = [
  {
    id: 'cimup-cesium-script',
    type: 'js',
    url: 'lib/cimup/Cesium/Cesium.js',
  },
  {
    id: 'cimup-script',
    type: 'js',
    url: 'lib/cimup/CIMUP.js',
  },
  {
    id: 'cimup-widgets',
    type: 'css',
    url: 'lib/cimup/Cesium/Widgets/widgets.css',
  },
];

const resourcePromises = resources.map(createResourceElement);

const particleIframeRef = ref();

onMounted(() => {
  loadResources();
});

onBeforeUnmount(() => {
  removeResources();
});

function back() {
  emits('closeHandle');
}

const saveConfirm = debounce(
  () => {
    const effectInfo: any = particleIframeRef.value.validateEffectInfo();
    if (!effectInfo) return;

    if (props.effect && props.effect.effectId) {
      const fData = new FormData();
      fData.set('effId', props.effect.effectId);
      fData.set('effName', effectInfo.form.effectName);
      fData.set('effCover', effectInfo.form.effCover);
      fData.set('configJson', effectInfo.json);
      editEffect({ data: fData }).then(() => {
        emits('closeHandle', effectInfo.json);
      });
    } else {
      const fData = new FormData();
      fData.set('effType', 4);
      fData.set('effName', effectInfo.form.effectName);
      fData.set('effDesp', '');
      fData.set('effCover', effectInfo.form.effCover);
      fData.set('quoteUrl', '');
      fData.set('configJson', effectInfo.json);
      createEffect({ data: fData }).then(() => {
        emits('closeHandle', effectInfo.json);
      });
    }
  },
  300,
  {
    leading: true,
    trailing: false,
  }
);

function createResourceElement(resourceInfo: Resource) {
  const { type, url, id } = resourceInfo;
  let resourceElement: any;

  if (type === 'js') {
    resourceElement = document.createElement('script');
    resourceElement.src = getAbsolutePath(url);
    resourceElement.async = true;
  } else if (type === 'css') {
    resourceElement = document.createElement('link');
    resourceElement.href = getAbsolutePath(url);
    resourceElement.rel = 'stylesheet';
  }

  resourceElement.id = id;

  return new Promise((resolve, reject) => {
    resourceElement.onload = resolve;
    resourceElement.onerror = reject;
    document.body.appendChild(resourceElement);
  });
}

function loadResources() {
  Promise.all(resourcePromises).then(() => {
    loaded.value = true;
    const { CIMUP, Cesium } = window;
    const cimInstance = CIMUP.CimEngine.instance;
    window.cimSettingInstance = cimInstance;
  });
}

function removeResources() {
  for (const { id } of resources) {
    const element = document.getElementById(id);
    element && document.body.removeChild(element);
  }
}
</script>

<style lang="less" scoped>
.particle-setting {
  position: fixed;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;
  z-index: 10;
  display: flex;
  flex-direction: column;
  .header {
    display: flex;
    align-items: center;
    flex-shrink: 0;
    height: 60px;
    background: #1d1e1f;
    border-bottom: 2px solid #000000;
    pointer-events: initial;
    padding: 0 20px 0 0;
    .left {
      display: flex;
      align-items: center;
      width: 30%;
      .back {
        display: flex;
        align-items: center;
        white-space: nowrap;
        margin-right: 24px;
        cursor: pointer;
        .svg-icon {
          margin-left: 12px;
          margin-right: 4px;
          font-size: 20px;
        }
      }
    }
    .el-button {
      margin-left: auto;
    }
  }
  .iframe-wrap {
    flex: 1;
    display: flex;
    iframe {
      width: 100%;
      height: 100%;
    }
  }
}

:deep(.btn-upload) {
  width: 32px;
  height: 32px;
  border: 1px solid #ccc;
  border-radius: 4px;
  display: flex;
  .svg-icon {
    margin: auto;
    font-size: 24px;
  }
}
:deep(.thumbnail-preview) {
  width: 100px;
}
</style>
